import {isELementNode, createError} from './util'
import {AddNodeBtnClassName, DelNodeBtnClassName} from './constant/index'
import {createMapNode } from './dom'
import {clearNodeObj, appendNode, removeNode, buildNodeRel, findNodeByEl} from './vnode'

const Distance = 30

const initEdit = (el, rootNode) => {
    if (!isELementNode(el)) throw createError(initEditinitEdit, 'first param need element')

    el.addEventListener('click', function(e){
        let target = e.target
        let node = null
        switch(target.className){
            case AddNodeBtnClassName:
                //必要的重复代码
                node = findNodeByEl(target.parentNode, rootNode)
                addMapNode(node)
                break
            case DelNodeBtnClassName:
                node = findNodeByEl(target.parentNode, rootNode)
                delMapNode(node)
                break
        }
    }, false)


    const addMapNode = (node, differX=0, differY=Distance,msg='您还没输入任何信息') => {
        
        let nodeEl = node.element,
        currentNodeRect = nodeEl.getBoundingClientRect(),
        bottom = currentNodeRect.bottom,
        left = currentNodeRect.left,
        newNode = createMapNode(msg, left+differX, bottom+differY)
        
        buildNodeRel(newNode, node)
        //新增后去掉btn
        hideDom(node.addBtnEl)
        appendNode(el, newNode)
    }
    
    const delMapNode = (node) => {
        if (!node) return null
        
        delMapNode(node.createdNode)
        node.creatByNode && showDom(node.creatByNode.addBtnEl)
        removeNode(el, node)
        clearNodeObj(node)
    }
}

const hideDom = dom => {
    if (!dom) return null
    dom.style.display = 'none'
}

const showDom = dom => {
    if (!dom) return null
    dom.style.display = 'block'
}


export default initEdit
